package com.wormhole.wormholemanagement.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.resource.PathResourceResolver;

import java.io.IOException;
import java.net.URLDecoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Value("${app.upload.dir:uploads/}")
    private String uploadDir;

    @Value("${baseDir}")
    private String baseDir;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/uploads/**")
                .addResourceLocations("file:" + uploadDir + "/");
        registry.addResourceHandler("/v3/api-docs/**")
                .addResourceLocations("classpath:/META-INF/resources/v3/api-docs/");
        registry.addResourceHandler("/static/**")
                .addResourceLocations("file:" + baseDir + "/")
                .setCachePeriod(3600)
                .resourceChain(true)
                .addResolver(new PathResourceResolver() {
                    @Override
                    protected Resource getResource(String resourcePath, Resource location) throws IOException {
                        String decodedPath = URLDecoder.decode(resourcePath, "UTF-8");
                        Path fullPath = Paths.get(baseDir, decodedPath).normalize();

                        // 打印调试信息
                        System.out.println("请求路径: " + resourcePath);
                        System.out.println("解码路径: " + decodedPath);
                        System.out.println("完整物理路径: " + fullPath);
                        System.out.println("文件是否存在: " + Files.exists(fullPath));

                        return super.getResource(decodedPath, location);
                    }
                });
    }
}